@echo off
:: Script to install G++ compiler using MSYS2 on Windows 11

:: Check if running as administrator
net session >nul 2>&1
if %errorLevel% == 0 (
    echo Running as administrator...
) else (
    echo Please run this script as administrator!
    pause
    exit /b
)

:: Set the download URL for MSYS2 installer
set MSYS2_URL=https://github.com/msys2/msys2-installer/releases/download/2023-03-18/msys2-x86_64-20230318.exe

:: Set the path to save the installer (Windows 11 default download directory)
set DOWNLOAD_PATH=%USERPROFILE%\Downloads\msys2-installer.exe

:: Download the MSYS2 installer using PowerShell
echo Downloading MSYS2 installer...
powershell -Command "Invoke-WebRequest -Uri '%MSYS2_URL%' -OutFile '%DOWNLOAD_PATH%'"

:: Check if the download was successful
if not exist "%DOWNLOAD_PATH%" (
    echo Failed to download MSYS2 installer!
    pause
    exit /b
)

:: Install MSYS2 if not already installed
if not exist "C:\msys64\usr\bin\bash.exe" (
    echo Installing MSYS2...
    echo Please follow the installation wizard to complete the installation.
    start /wait "" "%DOWNLOAD_PATH%"
) else (
    echo MSYS2 is already installed.
)

:: Set the path to MSYS2 bin directory
set MSYS2_BIN_PATH=C:\msys64\usr\bin

:: Check if G++ is already installed
where g++ >nul 2>&1
if %errorLevel% == 0 (
    echo G++ is already installed.
    goto CLEANUP
)

:: Add MSYS2 bin directory to the system PATH
echo Adding MSYS2 bin directory to system environment variables...
setx PATH "%PATH%;%MSYS2_BIN_PATH%" /M

:: Install G++ using MSYS2 pacman
echo Installing G++ using MSYS2 pacman...
C:\msys64\usr\bin\bash -lc "pacman -Syu --noconfirm"
C:\msys64\usr\bin\bash -lc "pacman -S --noconfirm mingw-w64-x86_64-gcc"

:: Verify if G++ is installed
where g++ >nul 2>&1
if %errorLevel% == 0 (
    echo G++ installation completed successfully!
) else (
    echo G++ installation failed!
)

:: Add MSYS2's g++ bin directory to system PATH (re-check)
set GPP_BIN_PATH=C:\msys64\mingw64\bin

:: Check if g++ is already in PATH
for /f "delims=" %%i in ('where g++ 2^>nul') do (
    set GPP_FOUND=%%i
)

:: If GPP_FOUND is empty, g++ is not in the PATH
if not defined GPP_FOUND (
    echo g++ is not in PATH.
) else (
    echo g++ is already in PATH: %GPP_FOUND%
)

:: Check if the bin directory exists
if not exist "%GPP_BIN_PATH%" (
    echo Error: The directory "%GPP_BIN_PATH%" does not exist.
    echo Please ensure MSYS2 is installed correctly and the G++ compiler is installed.
    pause
    exit /b
)

:: Add MSYS2's g++ bin directory to system PATH (final step)
echo Adding MSYS2's g++ to system environment variables...
setx PATH "%PATH%;%GPP_BIN_PATH%" /M

:: Verify if the PATH update is successful by starting a new cmd window with updated PATH
echo Verifying the update of PATH...
start cmd /K "where g++"

:CLEANUP
:: Clean up the installer
echo Cleaning up the installer...
del "%DOWNLOAD_PATH%"

pause
